<?php

namespace app\controller\api\v1\recovery;

use app\model\order\StoreOrder;
use app\model\user\User;
use app\model\v1\gift\GiftCard;
use app\model\v1\gift\GiftCardBless;
use app\model\v1\gift\GiftCardCate;
use app\model\v1\gift\GiftCardEffect;
use app\model\v1\gift\GiftCardNumber;
use app\model\v1\gift\GiftCardReport;
use app\model\v1\gift\GiftCardSys;
use app\model\v1\gift\GiftCardUser;
use app\model\v1\gift\GiftShareInfo;
use app\Request;
use app\services\order\StoreOrderCreateServices;
use app\validate\api\user\RegisterValidates;
use crmeb\services\CacheService;
use think\exception\ValidateException;

class GiftCardCollection
{
    protected $model;

    public function __construct(GiftCard $model)
    {
        $this->model = new GiftCard();
    }


    /**
     * 获取礼品卡列表
     * @param Request $request
     * @return \think\Response
     */
    public function getGiftCardList(Request $request)
    {
        $params = $request->param();
        $params["limit"] = $params['limit'] ?? 10;
        $params["page"] = $params['page'] ?? 1;

        $params['uid'] = $request->uid();
        $data = GiftCard::getGiftCardList($params);

        return app('json')->success($data);
    }



    /**
     * 礼品卡详情
     * @param Request $request
     * @return \think\Response
     */
    public function getGiftCardDetail(Request $request)
    {
        $params = $request->param();
        $id = $request->get('id', 0);
        if(empty($params['id']))  return app('json')->fail('id不能为空');

        $params['uid'] = $request->uid();
        $detail = GiftCard::getGiftCardDetail($params);

        return app('json')->success($detail ? $detail->toArray() : []);
    }


    /**
     * 礼品卡激活/领取
     * @param Request $request
     * @return \think\Response
     */
    public function activeGiftCard(Request $request)
    {
        $param = $request->post();
        if(empty($param['id']))  return app('json')->fail('id不能为空');
        if(empty($param['number']))  return app('json')->fail('number卡号不能为空');
        if(empty($param['card_pwd']))  return app('json')->fail('card_pwd密码不能为空');
        if(empty($param['rec_type']))  return app('json')->fail('rec_type不能为空');

        $msg = '激活成功';
        if($param['rec_type'] == 1) $msg = '领取成功';
        try {
            $param['uid'] = $request->uid();
            $res = GiftCardUser::activeGiftCard($param);

            return app('json')->success($msg);
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 自定义祝福语
     * @param Request $request
     * @return \think\Response
     */
    public function customGiftBless(Request $request)
    {
        $param = $request->post();
        if(empty($param['id']))  return app('json')->fail('id不能为空');
        if(empty($param['bless']))  return app('json')->fail('bless自定义祝福语不能为空');

        $res = GiftCardUser::where("id", $param['id'])->update(["bless"=>$param["bless"], "update_time"=>time()]);

        return app('json')->success('success');
    }


    /**
     * 获取祝福语背景图
     * @param Request $request
     * @return \think\Response
     */
    public function getCardGround(Request $request)
    {
        $param = $request->param();
        if(empty($param['card_id']))  return app('json')->fail('card_id不能为空');

        $data['ground'] = GiftCard::where("id", $param['card_id'])->value('ground') ?? '';

        return app('json')->success($data);
    }
	public function get_blessing_words(Request $request)
	{
		$param = $request->param();
		if(empty($param['card_id']))  return app('json')->fail('card_id不能为空');

		$data['ground'] = GiftCardBless::getBlessData($param['card_id']);

		return app('json')->success($data);
	}


    /**
     * 获取特效视频
     * @param Request $request
     * @return \think\Response
     */
    public function getCardEffect(Request $request)
    {
        $param = $request->param();
        if(empty($param['cate_id']))  return app('json')->fail('cate_id不能为空');

        $data = GiftCardEffect::whereNull("delete_time")->where("cate_id", $param['cate_id'])->where("status",1)->select()->toArray();
        return app('json')->success($data);
    }



    /**
     * 创建礼品卡订单
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createGiftOrder(Request $request)
    {
        $param = $request->post();
        if(empty($param['gift_card_id'])) return app('json')->fail('gift_card_id礼品卡id不能为空');
        if(empty($param['total_price'])) return app('json')->fail('total_price礼品卡金额不能为空');
        if(empty($param['pay_price'])) return app('json')->fail('pay_price实付金额不能为空');
        //if(empty($param['address_id'])) return app('json')->fail('address_id用户地址id不能为空');
        if(!empty($param['num'])){
            if(empty($param['price_text'])) return app('json')->fail('price_text不能为空');
            $price_text_arr = explode(",", $param["price_text"]);
            if(count($price_text_arr) < $param["num"]) return app('json')->fail('价格少于个数错误');
            if(count($price_text_arr) > $param["num"]) return app('json')->fail('价格多于个数错误');
        }

        try {
            $uid = $request->uid();

            $order_id = GiftCard::createGiftOrder($uid, $param);
            if (!$order_id) return app('json')->fail('创建礼品卡订单fail');

        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }

        return app('json')->success($order_id);
    }


    /**
     * 礼品卡标签类型
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCardCateTag(Request $request)
    {
        $data = GiftCardCate::where("status", 1)->order(["update_time"=>"desc", "id"=>"desc"])->select()->toArray();
        return app('json')->success($data);
    }


    /**
     * 全部订单列表
     * @param Request $request
     * @return \think\Response
     */
    public function getGiftOrderList(Request $request)
    {
        $param = $request->param();
        $param['page'] = $param['page'] ?? 1;
        $param['limit'] = $param['limit'] ?? 10;

        $uid = $request->uid();
        $data = GiftCard::getGiftOrderList($uid, $param);

        return app('json')->success($data);
    }


    /**
     * 取消/删除礼品卡订单
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function cancelGiftOrder(Request $request)
    {
        $param = $request->post();
        if(empty($param["order_id"])) return app('json')->fail('order_id不能为空');
        if(empty($param["type"])) return app('json')->fail('type不能为空');

        try {
            $res = GiftCard::cancelGiftOrder($param);

            return app('json')->success('success');
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 我的礼品卡 - 删除
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function delCardUser(Request $request)
    {
        $param = $request->post();
        if(empty($param["card_user_id"])) return app('json')->fail('card_user_id不能为空');

        try {
            $res = GiftCard::delCardUser($param);

            return app('json')->success('success');
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }



    /**
     * 礼品卡挂失-校验卡号
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function reportCheckNumber(Request $request)
    {
        $param = $request->param();
        if(empty($param["number"])) return app('json')->fail('number卡号不能为空');

        $msg = '卡号正确';
        $param["uid"] = $request->uid();
        $res = GiftCardUser::reportCheckNumber($param);
        if(!$res) $msg = '卡号错误';
        return app('json')->success($msg);
    }


    /**
     * 礼品卡挂失 - 身份校验
     * @param Request $request
     * @return \think\Response
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkReportGift(Request $request)
    {
        [$phone, $code, $username, $idcard] = $request->postMore([['phone', ''], ['code', ''], ['username', ''], ['idcard','']], true);

        $user_find = User::where("uid", $request->uid())->find();
        if(empty($user_find)) return app('json')->fail('用户不存在');

        //验证手机号
        try {
            validate(RegisterValidates::class)->scene('code')->check(['phone' => $phone]);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }

        //验证验证码
        $verifyCode = CacheService::get('code_' . $phone);
        if (!$verifyCode)
            return app('json')->fail('请先获取验证码');
        $verifyError = (int)CacheService::get('code_error_' . $phone);
        if ($verifyError >= 10) {
            return app('json')->fail('请稍后在获取');
        }
        $verifyCode = substr($verifyCode, 0, 6);
        if ($verifyCode != $code) {
            CacheService::set('code_error_' . $phone, $verifyError + 1, 180);
            return app('json')->fail('验证码错误');
        }

        $user_find = $user_find->toArray();
        if($user_find["phone"] == $phone) return app('json')->success('验证成功');
        return app('json')->fail('验证失败');
    }


    /**
     * 礼品卡挂失
     * @param Request $request
     * @return \think\Response
     */
    public function reportGiftCard(Request $request)
    {
        $param = $request->post();
        if(empty($param["number"])) return app('json')->fail('number卡号不能为空');
        if(empty($param["reason"])) return app('json')->fail('reason不能为空');
        if(empty($param["phone"])) return app('json')->fail('phone手机号不能为空');
        if(empty($param["user_name"])) return app('json')->fail('user_name姓名不能为空');

        try {
            $param["uid"] = $request->uid();
            $res = GiftCardUser::reportGiftCard($param);
            return app('json')->success('success');
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 获取相关配置
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGiftCarSys(Request $request)
    {
        $param = $request->param();
        if(empty($param["type"])) return app('json')->fail('type不能为空');

        $data = GiftCardSys::where("type", $param["type"])->select()->toArray();

        return app('json')->success($data);
    }


    /**
     * 获取挂失记录列表
     * @param Request $request
     * @return \think\Response
     */
    public function getGiftReportList(Request $request)
    {
        $param = $request->param();
        $param['page'] = $param['page'] ?? 1;
        $param['limit'] = $param['limit'] ?? 10;

        $param['uid'] = $request->uid();
        $data = GiftCardReport::getGiftReportList($param);

        return app('json')->success($data);
    }


    /**
     * 挂失补卡
     * @param Request $request
     * @return \think\Response
     */
    public function resetGiftCard(Request $request)
    {
        $param = $request->param();
        if(empty($param["card_user_id"])) return app('json')->fail('card_user_id不能为空');
        if(empty($param["address_id"])) return app('json')->fail('address_id不能为空');

        try {
            $param['uid'] = $request->uid();
            $data = GiftCardUser::resetGiftCard($param);
            return app('json')->success($data);
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 全部订单列表 - 确认收货
     * @param Request $request
     * @return \think\Response
     */
    public function confirmGiftCard(Request $request)
    {
        $param = $request->param();
        if(empty($param["order_id"])) return app('json')->fail('order_id不能为空');

        try {
            $param['uid'] = $request->uid();
            $res = GiftCardUser::confirmGiftCard($param);

            return app('json')->success('success');
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 我的礼品卡列表
     * @param Request $request
     * @return \think\Response
     */
    public function getGiftCardData(Request $request)
    {
        $param = $request->param();
        $param['page'] = $param['page'] ?? 1;
        $param['limit'] = $param['limit'] ?? 10;

        $uid = $request->uid();
        $data = GiftCardUser::getGiftCardData($uid, $param);

        return app('json')->success($data);
    }


    /**
     * 赠送记录列表
     * @param Request $request
     * @return \think\Response
     */
    public function getGiftCardRecord(Request $request)
    {
        $param = $request->param();
        $param['page'] = $param['page'] ?? 1;
        $param['limit'] = $param['limit'] ?? 10;

        $uid = $request->uid();
        $data = GiftCardUser::getGiftCardRecord($uid, $param);

        return app('json')->success($data);
    }


    /**
     * 分享礼品卡-自定义信息
     * @param Request $request
     * @return \think\Response
     */
    public function createCardShareInfo(Request $request)
    {
        $param = $request->post();
        if(empty($param["card_user_id"])) return app('json')->fail('card_user_id不能为空');

        try {
            $param["uid"] = $request->uid();
            $res = GiftShareInfo::createCardShareInfo($param);
            return app('json')->success('success');
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }


    /**
     * 分享礼品卡-自定义信息
     * @param Request $request
     * @return \think\Response
     */
    public function getCardShareInfo(Request $request)
    {
        $param = $request->post();
        if(empty($param["card_user_id"])) return app('json')->fail('card_user_id不能为空');

        $param["uid"] = $request->uid();
        $info = GiftShareInfo::getCardShareInfo($param);
        return app('json')->success($info ? $info->toArray() : []);
    }



    /**
     * 激活绑定实体卡
     * @param Request $request
     * @return \think\Response
     */
    public function bindCardNumber(Request $request)
    {
        $param = $request->post();
        if(empty($param['number'])) return app('json')->fail('number不能为空');
        if(empty($param['card_pwd'])) return app('json')->fail('card_pwd礼品卡金额不能为空');
        if(empty($param['phone'])) return app('json')->fail('phone手机号后4位不能为空');

        try {
            $uid = $request->uid();
            $param["uid"] = $uid;
            $res = GiftCardUser::bindCardNumber($param);

        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
        return app('json')->success("success");
    }



    /**
     * 购买礼品卡-保存编辑祝福语
     * @param Request $request
     * @return \think\Response
     */
    public function saveGiftShareInfo(Request $request)
    {
        $param = $request->post();
        if(empty($param["card_id"])) return app('json')->fail('card_id不能为空');

        try {
            $param["uid"] = $request->uid();
            $res = GiftShareInfo::saveGiftShareInfo($param);
            return app('json')->success($res);
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }


    public function getGiftShareInfo(Request $request)
    {
        $param = $request->post();
        ////if(empty($param["card_id"])) return app('json')->fail('card_id不能为空');

        $param["uid"] = $request->uid();
        $info = GiftShareInfo::getGiftShareInfo($param);
        return app('json')->success($info ? $info->toArray() : []);
    }


    public function associationGiftOrderId(Request $request)
    {
        $param = $request->post();
        if(empty($param["order_id"])) return app('json')->fail('order_id不能为空');
        if(empty($param["share_info_id"])) return app('json')->fail('share_info_id不能为空');

        try {
            $param["uid"] = $request->uid();
            $res = GiftShareInfo::associationGiftOrderId($param);
            return app('json')->success('success');
        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }
    }





    /**
     * 制作实体卡
     * @param Request $request
     * @return \think\Response
     */
    public function factureCardNumber(Request $request)
    {
        $param = $request->post();
        if(empty($param['address_id'])) return app('json')->fail('请选择地址');
        if(empty($param['gift_card_id'])) return app('json')->fail('gift_card_id礼品卡id不能为空');
        if(empty($param['number'])) return app('json')->fail('number卡号不能为空');

        if(empty($param['tag_id'])) return app('json')->fail('tag_id不能为空');
        if(!in_array($param['tag_id'], [1,10])) return app('json')->fail('只有领导卡和员工卡可以制作实体卡！');

        try {
            $uid = $request->uid();
            $param["uid"] = $uid;

            $find = GiftCardUser::where("number", $param['number'])->find();
            $find = $find->toArray();
            $number_ids = GiftCardNumber::setUseUid(1, $param['uid'], $param['gift_card_id']);

            $number_data = GiftCardNumber::getNumberByIds($number_ids);
            for ($i = 0; $i < count($number_ids); $i++) {
                $add_card_user = [
                    "uid" => $uid,
                    "gift_card_id" => $param['gift_card_id'],
                    "order_id" => $find['order_id'],
                    "type" => 1,
                    "type_bak" => 1,
                    "card_type" => 2,
                    "create_time" => time(),
                    "number" => $number_data[$i]["card_number"] ?? '',
                    'address_id' => $param['address_id'] ?? '',
                    'price_text' => $find['price_text'] ?? '',
                    "card_pwd" => $number_data[$i]["card_password"] ?? '',
                    "custom_price" => $find['custom_price'] ?? null,
                ];
                GiftCardUser::create($add_card_user);
            }
            GiftCardUser::where("id", $find['id'])->update(["status" => 10, "delete_time" => time()]);

        }catch (\Throwable $e){
            return app('json')->fail($e->getMessage());
        }

        return app('json')->success("success");
    }


}